
import pymysql
import json
from zhongsou.jd import JdApi


def getRegionList(query):

    host = '61.135.210.175'
    port = 3306
    user = 'flymall'
    pwd = 'fly2@15mall'
    db = 'flymall'

    conn = pymysql.connect(host=host, port=port, user=user, passwd=pwd, db=db, charset='UTF8')
    cur = conn.cursor()

    sql = "select region_id, region_name, parent_id, region_type, agency_id from b2c_region where %s" % query
    cur.execute(sql)

    address = []

    for r in cur:
#        print("index:" + str(cur.rownumber) + str(r))
        address.append({
            'region_id'   : int(r[0]),
            'region_name' : str(r[1]),
            'parent_id'   : int(r[2]),
            'region_type' : int(r[3]),
            'agency_id'   : int(r[4])
        })

    cur.close()
    conn.close()

    return address

def getJdAddress(type, agency_id):

    method = 'biz.address.townsByCountyId.query'
    if(type == 1):
        method = 'biz.address.allProvinces.query'
    elif(type == 2):
        method = 'biz.address.citysByProvinceId.query'
    elif (type == 3):
        method = 'biz.address.countysByCityId.query'
    elif (type == 4):
        method = 'biz.address.townsByCountyId.query'

    jdOutput = JdApi.execute(method, "{'id':%d}" % agency_id)

    result = None
    if(jdOutput.find('errorResponse') == -1):
        result = json.loads(jdOutput)[method.replace('.', '_') + "_response"]

    return result


if(__name__ == '__main__'):

    file = open("E:\\addr.txt", 'a')
    file2 = open("E:\\addrId.txt", 'a')

    list = []

    for index, addr in enumerate(getRegionList('region_type = 3 and agency_id > 0  and parent_id not in (52, 321, 343, 394) limit 2725, 1000')):
        jdAddr = getJdAddress(4, int(addr['agency_id']))
        if(jdAddr['result'] == None):
            pass
        else:
            print(jdAddr['result'].values())

            list4 = getRegionList('region_type = 4 and agency_id > 0 and parent_id = ' + str(addr['region_id']))
            for l4 in list4:
                if(l4['agency_id'] not in jdAddr['result'].values()):
                    print(str(l4) + '#######')
                    list.append(l4)
                    file.write(str(l4) + '\n')
                    file2.write(str(l4['region_id']) + ',')

        print(str(index) + '*' * 10)


    file.flush()
    file.close()

    file2.flush()
    file2.close()

    print('finished')

